'use strict'

const path = require('path')
const inspect = require('util').inspect

const Koa = require('koa')
const Router = require('koa-router')
const session = require('koa-session');
const views = require('koa-views')
const bodyParser = require('koa-bodyparser')
const Busboy = require('busboy')
const statics = require('koa-static')
const convert = require('koa-convert')
const sha1 = require('sha1')
const Promise = require('bluebird')
const request = Promise.promisify(require('request'))
const wechat = require('./wechat/g')
const util = require('./libs/utils/filetool')
const uploadFile = require('./libs/utils/upload')

const wechat_token_file = path.join(__dirname,'./config/token.txt')
// 静态资源目录对于相对入口文件index.js的路径
const staticPath = './static'

var config = {
    wechat:{
        appId:'wx8c3345796515d4db',
        appSecret:'7c16efcaf0f78997d1bba014d778718c',
        token:'Token1',
        getAccessToken:function () {
            return util.readFileAsync(wechat_token_file)
        },
        saveAccessToken:function (data) {
            data = JSON.stringify(data)
            return util.writeFileAsync(wechat_token_file,data)
        }
    },
    session:{
        key: 'koa:sess', /** (string) cookie key (default is koa:sess) */
        /** (number || 'session') maxAge in ms (default is 1 days) */
        /** 'session' will result in a cookie that expires when session/browser is closed */
        /** Warning: If a session cookie is stolen, this cookie will never expire */
        maxAge: 86400000,
        overwrite: true, /** (boolean) can overwrite or not (default true) */
        httpOnly: true, /** (boolean) httpOnly or not (default true) */
        signed: true, /** (boolean) signed or not (default true) */
        rolling: false,
    }
}

const  app = new Koa()
app.keys = ['some secret hurr'];

//使用session
app.use(session(config.session, app));

//静态资源
const root = path.join( __dirname,  staticPath)
console.log(root)
app.use(statics(root))

// 加载模板引擎
app.use(views(path.join(__dirname, './view'), {
    extension: 'ejs'
}))



let home = new Router()

// 子路由1
home.get('/', async ( ctx )=>{
    let title = 'hello koa2'

    await ctx.render('index', {
        title,
    })
})

// 子路由2
let page = new Router()
page.get('/404', async ( ctx )=>{
    ctx.body = '404 page!'
}).get('/helloworld', async ( ctx )=>{
    ctx.body = 'helloworld page!'
}).post('/post',async(ctx,next) => {
    // 当POST请求的时候，中间件koa-bodyparser解析POST表单里的数据，并显示出来
    let postData = ctx.request.body
    ctx.response.body = 'dddd'
    console.log(postData)
    //await next()
}).get('/post',async ( ctx,next)=>{

    // 当GET请求时候返回表单页面
    let html = `
      <h1>koa2 request post demo</h1>
      <form method="POST" action="/page/post/">
        <p>userName</p>
        <input name="userName" /><br/>
        <p>nickName</p>
        <input name="nickName" /><br/>
        <p>email</p>
        <input name="email" /><br/>
        <button type="submit">submit</button>
      </form>
    `
    ctx.body = html
    await next()
}).post('/upload',async(ctx)=>{
    // 上传文件请求处理
    let result = { success: false }
    let serverFilePath = path.join( __dirname, 'static/image' )

    // 上传文件事件
    result = await uploadFile( ctx, {
        fileType: 'album',
        path: serverFilePath
    })
    ctx.body = result
}).get('/upload',async(ctx)=>{
    await  ctx.render('upload')
})

let weixin = new Router()
weixin.use(wechat(config.wechat))


// 装载所有子路由
let router = new Router()
router.use('/', home.routes(), home.allowedMethods())
router.use('/page', page.routes(), page.allowedMethods())
router.use('/weixin/api', weixin.routes(), weixin.allowedMethods())


// 使用ctx.body解析中间件
app.use(bodyParser())
// 加载路由中间件
app.use(router.routes()).use(router.allowedMethods())




app.use(async(ctx,next) => {
    //ctx.body = 'hello koa2'
    console.log(ctx.query)
    //ctx.body = 'ddd'
    await next()

})

function setSession(cxt) {
    let n = ctx.session.views || 0;
    ctx.session.views = ++n;
    console.log(ctx.session);
}

function setCookie(ctx) {
    ctx.cookies.set(
        'cid',
        'hello world',
        {
            domain: 'localhost',  // 写cookie所在的域名
            path: '/index',       // 写cookie所在的路径
            maxAge: 10 * 60 * 1000, // cookie有效时长
            expires: new Date('2017-02-15'),  // cookie失效时间
            httpOnly: false,  // 是否只用于http请求中获取
            overwrite: false  // 是否允许重写
        }
    )
}

// 解析上下文里node原生请求的POST参数
function parsePostData( ctx ) {
    return new Promise((resolve, reject) => {
        try {
            let postdata = "";
            ctx.req.addListener('data', (data) => {
                postdata += data
            })
            ctx.req.addListener("end",function(){
                let parseData = parseQueryStr( postdata )
                resolve( parseData )
            })
        } catch ( err ) {
            reject(err)
        }
    })
}

// 将POST请求参数字符串解析成JSON
function parseQueryStr( queryStr ) {
    let queryData = {}
    let queryStrList = queryStr.split('&')
    console.log( queryStrList )
    for (  let [ index, queryStr ] of queryStrList.entries()  ) {
        let itemList = queryStr.split('=')
        queryData[ itemList[0] ] = decodeURIComponent(itemList[1])
    }
    return queryData
}

app.listen(8008)
console.log('[demo] start-quick is starting at port 8008')
//console.log(typeof config.wechat.getAccessToken())

module.exports = app